package com.wispx.gateway.core.filter.loadblance;

import com.wispx.gateway.core.filter.loadblance.strategy.ClientIpLoadBalanceStrategy;
import com.wispx.gateway.core.filter.loadblance.strategy.LoadBalanceStrategy;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

/**
 * 负载均衡策略管理
 */
@Slf4j
public class LoadBalanceStrategyManager {
    private static final Map<String, LoadBalanceStrategy> loadBalanceStrategyMap = new HashMap<>();

    static {
        ServiceLoader<LoadBalanceStrategy> loadBalanceStrategies = ServiceLoader.load(LoadBalanceStrategy.class);
        for (LoadBalanceStrategy loadBalanceStrategy : loadBalanceStrategies) {
            if (loadBalanceStrategy == null) continue;
            loadBalanceStrategyMap.put(loadBalanceStrategy.mark(), loadBalanceStrategy);
            log.info("success load load-balance strategy:{}", loadBalanceStrategy.mark());
        }
    }

    public static LoadBalanceStrategy getLoadBalanceStrategy(String strategyName) {
        return loadBalanceStrategyMap.getOrDefault(strategyName, new ClientIpLoadBalanceStrategy());
    }

}
